package com.kaifamiao.listener;

import com.kaifamiao.listener.entity.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.logging.Logger;

@WebServlet( "/user/*" )
public class UserServlet extends HttpServlet {

    private Logger logger = Logger.getLogger( this.getClass().getName() );

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        logger.info( "注销登录" );
        HttpSession session = request.getSession();
        // 将 删除 user 属性就是解除 User对象 与 会话对象 的绑定，此时会调用 valueUnbound 方法
        session.removeAttribute( "user" ); // 仅删除 user 属性
        // session.invalidate(); 废弃整个会话
        response.sendRedirect( request.getContextPath() + "/index.jsp" );
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        logger.info( "登录" );
        HttpSession session = request.getSession();
        // 从表单中获取请求参数
        String loginName = request.getParameter( "loginName" );
        String password = request.getParameter( "password" );
        if( "kaifamiao".equals( loginName ) && "hello2022".equals( password ) ){
            User u = new User( loginName , password );
            // 将 u 对象 作为 属性值 绑定到 会话对象 后，就会调用 u.valueBound 方法
            session.setAttribute( "user" , u );
        }
        response.sendRedirect( request.getContextPath() + "/index.jsp" );
    }

}
